import React, {Component} from 'react';
import Icon from 'react-native-vector-icons/Ionicons';
import Video from 'react-native-video';
import Button from 'react-native-button';
import {
  StyleSheet,
  Text,
  View,
  Dimensions,
  ActivityIndicator,
  TouchableOpacity,
  Image,
  ListView,
  TextInput,
  Modal,
  AlertIOS
} from 'react-native';

import request from '../common/request';
import config from '../common/config';

let width = Dimensions.get('window').width;
let cachedResults = {
  nextPage: 1,
  items: [],
  total: 0
};

export default class Detail extends Component {
  constructor(props) {
    super(props);
    let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      data: this.props.data,
      //comments
      dataSource: ds.cloneWithRows([]),

      //video player
      rate: 1,
      muted: false,
      resizeMode: 'contain',
      repeat: false,
      //video load
      videoLoaded: false,
      playing: false,
      videoOk: true,
      paused: false,
      videoProgress: 0.01,
      videoTotal: 0,
      currentTime: 0,

      //comment modal
      animationType: 'none',
      modalVisible: false,
      isSending: false,
      content: ''
    }
  }

  render() {
    let data = this.state.data;
    return (
      <View style={styles.container}>
        <View style={styles.header}>
          <TouchableOpacity style={styles.backBox} onPress={this._pop.bind(this)}>
            <Icon name='ios-arrow-back' style={styles.backIcon}/>
            <Text style={styles.backText}>返回</Text>
          </TouchableOpacity>
          <Text style={styles.headerTitle} numberOfLines={1}>视频详情页</Text>
        </View>
        <Text>{data.title}</Text>
        <View style={styles.videoBox}>
          <Video ref={(ref) => {
            this.player = ref
          }} source={{uri: data.video}} style={styles.video} volume={3} paused={this.state.paused}
                 rate={this.state.rate} muted={this.state.muted} resizeMode={this.state.resizeMode}
                 repeat={this.state.repeat} onLoadStart={this._onLoadStart.bind(this)} onLoad={this._onLoad.bind(this)}
                 onProgress={this._onProgress.bind(this)} onEnd={this._onEnd.bind(this)}
                 onError={this._onError.bind(this)}/>

          {
            !this.state.videoOk && <Text style={styles.failText}>视频出错！很抱歉</Text>
          }
          {
            !this.state.videoLoaded && <ActivityIndicator color='#ee735c' style={styles.loading}/>
          }
          {
            this.state.videoLoaded && !this.state.playing ?
              <Icon onPress={this._replay.bind(this)} name='ios-play' size={48} style={styles.playIcon}/> : null
          }
          {
            this.state.videoLoaded && this.state.playing ?
              <TouchableOpacity onPress={this._pause.bind(this)} style={styles.pauseBtn}>
                {
                  this.state.paused ?
                    <Icon onPress={this._resume.bind(this)} name='ios-play' size={48} style={styles.resumeIcon}/> :
                    <Text/>
                }
              </TouchableOpacity> : null
          }

          <View style={styles.progressBox}>
            <View style={[styles.progressBar, {width: width * this.state.videoProgress}]}/>
          </View>
        </View>

        <ListView
          dataSource={this.state.dataSource}
          renderRow={this._renderRow.bind(this)}
          renderHeader={this._renderHeader.bind(this)}
          renderFooter={this._renderFooter.bind(this)}
          onEndReached={this._fetchMoreData.bind(this)}
          onEndReachedThreshold={20}
          enableEmptySections={true}
          showsVerticalScrollIndicator={false}
          automaticallyAdjustContentInsets={false}
        />

        <Modal animationType={'fade'} visible={this.state.modalVisible} onRequestClose={() => {
          this._setModalVisible(false)
        }}>
          <View style={styles.modalContainer}>
            <Icon onPress={this._closeModal.bind(this)} name='ios-close-outline' style={styles.closeIcon}/>
            <View style={styles.commentBox}>
              <View style={styles.comment}>
                <TextInput placeholder='请评论。。。' style={styles.content} multiline={true}
                           defaultValue={this.state.content} onChangeText={(text) => {
                  this.setState({
                    content: text
                  })
                }}/>
              </View>
            </View>
            <Button style={styles.submitBtn} onPress={this._submit.bind(this)}>评论</Button>
          </View>
        </Modal>
      </View>
    )
  }

  componentDidMount() {
    this._fetchData();
  }

  _renderRow(row) {
    return (
      <View key={row._id} style={styles.replyBox}>
        <Image style={styles.replyAvatar} source={{uri: row.replyBy.avatar}}/>
        <View style={styles.reply}>
          <Text style={styles.replyNickname}>{row.replyBy.nickname}</Text>
          <Text style={styles.replyContent}>{row.content}</Text>
        </View>
      </View>
    )
  }

  //video
  _onLoadStart() {

  }

  _onLoad() {

  }

  _onProgress(data) {
    // if (!this.state.videoLoaded) {
    //   this.setState({
    //     videoLoaded: true
    //   })
    // }
    //console.log(data);

    let duration = data.playableDuration;
    let currentTime = data.currentTime;
    let percent = Number((currentTime / duration).toFixed(2));
    let newState = {
      videoTotal: duration,
      currentTime: Number(data.currentTime.toFixed(2)),
      videoProgress: percent
    };
    if (!this.state.videoLoaded) {
      newState.videoLoaded = true;
    }
    if (!this.state.playing) {
      newState.playing = true;
    }
    this.setState(newState);
    // if(currentTime===duration){
    //   this.setState({
    //     playing:false
    //   })
    // }
  }

  _onEnd() {
    this.setState({
      videoProgress: 1,
      playing: false
    })
  }

  _onError() {
    this.setState({
      videoOk: false
    })
  }

  _replay() {
    // this.refs.videoPlayer.seek(0)
    this.player.seek(0)
  }

  _pause() {
    if (!this.state.paused) {
      this.setState({
        paused: true
      })
    }
  }

  _resume() {
    if (this.state.paused) {
      this.setState({
        paused: false
      })
    }
  }

  _pop() {
    this.props.navigator.pop()
  }

  //listview
  // _fetchData() {
  //   let that = this;
  //   let url = config.api.base + config.api.comment;
  //
  //   request.get(url, {
  //     id: that.state.data._id,
  //     accessToken: 'abc'
  //   }).then(function (data) {
  //     if (data && data.success) {
  //       let comments = data.data;
  //       if (comments && comments.length > 0) {
  //         that.setState({
  //           comments: comments,
  //           dataSource: that.state.dataSource.cloneWithRows(comments)
  //         })
  //       }
  //     }
  //   })
  //     .catch((err) => {
  //       console.log(err)
  //     })
  // }

  _fetchData(page) {
    let that = this;

    this.setState({
      isLoadingTail: true
    });

    request.get(config.api.base + config.api.comment, {accessToken: 'abc', page: page, creation: 123})
      .then((data) => {
        if (data.success) {
          let items = cachedResults.items.slice();

          items = items.concat(data.data);
          cachedResults.nextPage += 1;
          cachedResults.items = items;
          cachedResults.total = data.total;

          that.setState({
            isLoadingTail: false,
            dataSource: that.state.dataSource.cloneWithRows(cachedResults.items)
          });
        }
      })
      .catch((error) => {
        this.setState({
          isLoadingTail: false
        });
        console.error(error);
      })
  }

  _fetchMoreData() {
    if (!this._hasMore() || this.state.isLoadingTail) {
      return;
    }
    let page = cachedResults.nextPage;
    this._fetchData(page);
  }

  _hasMore() {
    return cachedResults.items.length !== cachedResults.total;
  }

  _renderFooter() {
    if (!this._hasMore() && cachedResults.total !== 0) {
      return (
        <View style={styles.loadingMore}>
          <Text style={styles.loadingText}>没有更多了</Text>
        </View>
      )
    }
    if (!this.state.isLoadingTail) {
      return <View style={styles.loadingMore}/>
    }
    return (
      <ActivityIndicator style={styles.loadingMore}/>
    );
  }

  _renderHeader() {
    let data = this.state.data;
    return (
      <View style={styles.listHeader}>
        <View style={styles.infoBox}>
          <Image style={styles.avatar} source={{uri: data.author.avatar}}/>
          <View style={styles.descBox}>
            <Text style={styles.nickname}>{data.author.nickname}</Text>
            <Text style={styles.title}>{data.title}</Text>
          </View>
        </View>
        <View style={styles.commentBox}>
          <View style={styles.comment}>
            <TextInput placeholder='请评论。。。' style={styles.content} multiline={true} onFocus={this._focus.bind(this)}/>
          </View>
        </View>
        <View style={styles.commentArea}>
          <Text style={styles.commentTitle}>精彩评论</Text>
        </View>
      </View>
    )
  }

  //comment
  _focus() {
    this._setModalVisible(true)
  }

  _submit() {
    let that = this;
    if (!this.state.content) {
      return AlertIOS.alert('留言不能为空！')
    }
    if (this.state.isSending) {
      return AlertIOS.alert('正在评论中！')
    }

    this.setState({
      isSending: true
    }, function () {
      let body = {
        accessToken: 'abc',
        creation: '123',
        content: this.state.content
      };
      let url = config.api.base + config.api.comment;

      request.post(url, body)
        .then(function (data) {
          if (data && data.success) {
            let items = cachedResults.items.slice();
            let content = that.state.content;

            items = [{
              content: content,
              replyBy: {
                avatar: 'http://dummyimage.com/640x640/6bd469)',
                nickname: 'nickname'
              }
            }].concat(items);

            cachedResults.items = items;
            cachedResults.total += 1;

            that.setState({
              content: '',
              isSending: false,
              dataSource: that.state.dataSource.cloneWithRows(cachedResults.items)
            });

            that._setModalVisible(false);
          }
        })
        .catch((err) => {
          console.log(err);
          that.setState({
            isSending: false
          });
          that._setModalVisible(false);
          AlertIOS.alert('留言失败，稍后重试！');
        })
    })
  }

  _closeModal() {
    this._setModalVisible(false)
  }

  _setModalVisible(isVisible) {
    this.setState({
      modalVisible: isVisible
    })
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF',
  },
  //顶部
  header: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    width: width,
    height: 64,
    paddingLeft: 10,
    paddingRight: 10,
    paddingTop: 20,
    borderBottomWidth: 1,
    borderColor: 'rgba(0,0,0,0.1)',
    backgroundColor: '#fff'
  },
  backBox: {
    position: 'absolute',
    flexDirection: 'row',
    alignItems: 'center',
    top: 32,
    left: 12,
    width: 50
  },
  headerTitle: {
    width: width - 120,
    textAlign: 'center'
  },
  backIcon: {
    color: '#999',
    fontSize: 20,
    marginRight: 5
  },
  backText: {
    color: '#999'
  },

  //video视频
  videoBox: {
    width: width,
    height: width * 0.56,
    backgroundColor: '#000'
  },
  video: {
    width: width,
    height: width * 0.56,
    backgroundColor: '#000'
  },
  loading: {
    position: 'absolute',
    left: 0,
    top: 80,
    width: width,
    alignSelf: 'center',
    backgroundColor: 'transparent'
  },
  progressBox: {
    width: width,
    height: 2,
    backgroundColor: '#ccc'
  },
  progressBar: {
    width: 1,
    height: 2,
    backgroundColor: '#ff6600'
  },
  playIcon: {
    position: 'absolute',
    top: 80,
    left: width / 2 - 30,
    height: 60,
    width: 60,
    paddingTop: 8,
    paddingLeft: 22,
    backgroundColor: 'transparent',
    borderColor: '#fff',
    borderRadius: 30,
    borderWidth: 1,
    color: '#ed7b66'
  },
  pauseBtn: {
    position: 'absolute',
    top: 0,
    left: 0,
    width: width,
    height: width * 0.56
  },
  resumeIcon: {
    position: 'absolute',
    top: 80,
    left: width / 2 - 30,
    height: 60,
    width: 60,
    paddingTop: 8,
    paddingLeft: 22,
    backgroundColor: 'transparent',
    borderColor: '#fff',
    borderRadius: 30,
    borderWidth: 1,
    color: '#ed7b66'
  },
  failText: {
    position: 'absolute',
    left: 0,
    top: 90,
    width: width,
    textAlign: 'center',
    color: '#fff',
    backgroundColor: 'transparent'
  },

  //视频作者介绍
  infoBox: {
    width: width,
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: 10
  },
  avatar: {
    width: 60,
    height: 60,
    marginRight: 10,
    marginLeft: 10,
    borderRadius: 30
  },
  descBox: {
    flex: 1
  },
  nickname: {
    fontSize: 18
  },
  title: {
    marginTop: 8,
    fontSize: 16,
    color: '#666'
  },

  //评论列表
  replyBox: {
    flexDirection: 'row',
    justifyContent: 'flex-start',
    marginTop: 10
  },
  replyAvatar: {
    width: 40,
    height: 40,
    borderRadius: 20,
    marginRight: 10,
    marginLeft: 10
  },
  replyNickname: {
    color: '#666'
  },
  replyContent: {
    color: '#666',
    marginTop: 4
  },
  reply: {
    flex: 1
  },
  loadingMore: {
    marginVertical: 20
  },
  loadingText: {
    color: '#777',
    textAlign: 'center'
  },
  commentArea: {
    width: width,
    paddingBottom: 6,
    paddingLeft: 10,
    paddingRight: 10,
    borderBottomWidth: 1,
    borderBottomColor: '#eee'
  },

  //评论框
  listHeader: {
    width: width,
    marginTop: 10
  },
  commentBox: {
    marginTop: 10,
    marginBottom: 10,
    padding: 8,
    width: width
  },
  content: {
    paddingLeft: 2,
    color: '#333',
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 4,
    fontSize: 14,
    height: 80
  },
  modalContainer: {
    flex: 1,
    paddingTop: 45,
    backgroundColor: '#fff'
  },
  closeIcon: {
    alignSelf: 'center',
    fontSize: 30,
    color: '#ee753c'
  },
  submitBtn: {
    width: width - 20,
    padding: 16,
    marginTop: 20,
    marginBottom: 20,
    borderWidth: 1,
    borderRadius: 4,
    borderColor: '#ee735c',
    fontSize: 18,
    color: '#ee735c'
  }
});